<?php


namespace app\common\service\system;

use app\common\cache\system\NoticeCache;
use app\common\model\system\NoticeModel;

/**
 * 公告管理
 */
class NoticeService
{
    /**
     * 添加修改字段
     * @var array
     */
    public static $edit_field = [
        'notice_id/d'   => '',
        'image_id/d'    => 0,
        'type/d'        => 1,
        'title/s'       => '',
        'title_color/s' => '',
        'start_time/s'  => '',
        'end_time/s'    => '',
        'desc/s'        => '',
        'content/s'     => '',
        'remark/s'      => '',
        'sort/d'        => 250,
        'is_terminal/d'=> 1,
        'merchant_id/a'=>[],
        'member_id/a'=> [],
    ];

    /**
     * 公告列表
     *
     * @param array  $where 条件
     * @param int    $page  页数
     * @param int    $limit 数量
     * @param array  $order 排序
     * @param string $field 字段
     * 
     * @return array 
     */
    public static function list($where = [], $page = 1, $limit = 10, $order = [], $field = '')
    {
        $model = new NoticeModel();
        $pk = $model->getPk();

        if (empty($field)) {
            $field = $pk . ',image_id,is_terminal,merchant_id,member_id,type,title,title_color,start_time,end_time,is_disable,sort,create_time,update_time,remark';
        }
        if (empty($order)) {
            $order = [$pk => 'desc'];
        }
        $with =['member'=>function ($query) {
            $query->field('member_id,nickname');
        }];
        $append = $hidden = $field_no = [];
        if (strpos($field, 'image_id') !== false) {
            $with[]   = $hidden[] = 'image';
            $append[] = 'image_url';
        }
        if (strpos($field, 'type') !== false) {
            $append[] = 'type_name';
        }
        $fields = explode(',', $field);
        foreach ($fields as $k => $v) {
            if (in_array($v, $field_no)) {
                unset($fields[$k]);
            }
        }
        $field = implode(',', $fields);

        $count = $model->where($where)->count();
        $pages = 0;
        if ($page > 0) {
            $model = $model->page($page);
        }
        if ($limit > 0) {
            $model = $model->limit($limit);
            $pages = ceil($count / $limit);
        }
        $merchantId = mer_id();
        $list = $model->field($field)
            ->when($merchantId>0, function($query) use ($merchantId) {
                $query->where(function($quer)use ($merchantId) {
                    $quer->where('merchant_id', $merchantId)->whereOr('merchant_id',null);
                });
            })
            ->where($where)
            ->with($with)->append($append)->hidden($hidden)
            ->order($order)->select()->toArray();
        return compact('count', 'pages', 'page', 'limit', 'list');
    }

    /**
     * 公告信息
     *
     * @param int  $id   公告id
     * @param bool $exce 不存在是否抛出异常
     * 
     * @return array|Exception
     */
    public static function info($id, $exce = true)
    {
        $info = NoticeCache::get($id);
        if (empty($info)) {
            $model = new NoticeModel();

            $info = $model->find($id);
            if (empty($info)) {
                if ($exce) {
                    exception('公告不存在：' . $id);
                }
                return [];
            }
            $info = $info->append(['image_url'])->hidden(['image'])->toArray();

            NoticeCache::set($id, $info);
        }

        return $info;
    }

    /**
     * 公告添加
     *
     * @param array $param 公告信息
     * 
     * @return array|Exception
     */
    public static function add($param)
    {
        $model = new NoticeModel();
        $pk = $model->getPk();

        unset($param[$pk]);
        $data = array();
        $create_uid = user_id();
        if($param['is_terminal'] == 1 && isset($param['merchant_id']) && count($param['merchant_id'])>0){
            foreach ($param['merchant_id'] as $key=>$val){
                array_push($data,[
                    'is_terminal'=>$param['is_terminal'],//终端：1、商家端 2、买家端
                    'merchant_id'=>$val,//商家ID
                    'member_id'=>null,//买家ID
                    'type'=>1,//类型：0通知，1公告，mock(@natural(0, 1))
                    'title'=>$param['title'],//标题，mock(@ctitle(10, 20))
                    'title_color'=>$param['title_color'],//标题颜色，mock(@color)
                    'content'=>$param['content'],//内容，mock(@cparagraph(15, 90))
                    'remark'=>$param['remark'],//备注，mock(@csentence(5, 10))
                    'sort'=>$param['sort'],//排序
                    'create_uid'=>$create_uid,
                    'create_time'=>datetime()
                ]);
            }
        }else if($param['is_terminal'] == 2 && isset($param['member_id']) && count($param['member_id'])>0){
            foreach ($param['member_id'] as $key=>$val){
                array_push($data,[
                    'is_terminal'=>$param['is_terminal'],//终端：1、商家端 2、买家端
                    'merchant_id'=>null,//商家ID
                    'member_id'=>$val,//买家ID
                    'type'=>1,//类型：0通知，1公告，mock(@natural(0, 1))
                    'title'=>$param['title'],//标题，mock(@ctitle(10, 20))
                    'title_color'=>$param['title_color'],//标题颜色，mock(@color)
                    'content'=>$param['content'],//内容，mock(@cparagraph(15, 90))
                    'remark'=>$param['remark'],//备注，mock(@csentence(5, 10))
                    'sort'=>$param['sort'],//排序
                    'create_uid'=>$create_uid,
                    'create_time'=>datetime()
                ]);
            }
        }else{
            array_push($data,[
                'is_terminal'=>$param['is_terminal'],//终端：1、商家端 2、买家端
                'merchant_id'=>null,//商家ID
                'member_id'=>null,//买家ID
                'type'=>1,//类型：0通知，1公告，mock(@natural(0, 1))
                'title'=>$param['title'],//标题，mock(@ctitle(10, 20))
                'title_color'=>$param['title_color'],//标题颜色，mock(@color)
                'content'=>$param['content'],//内容，mock(@cparagraph(15, 90))
                'remark'=>$param['remark'],//备注，mock(@csentence(5, 10))
                'sort'=>$param['sort'],//排序
                'create_uid'=>$create_uid,
                'create_time'=>datetime()
            ]);
        }

        $res = $model->insertAll($data);
        if (!$res) {
            exception();
        }
        return $data;
    }

    /**
     * 公告修改
     *
     * @param int|array $ids   公告id
     * @param array     $param 公告信息
     * 
     * @return array|Exception
     */
    public static function edit($ids, $param = [])
    {
        $model = new NoticeModel();
        $pk = $model->getPk();

        unset($param[$pk], $param['ids'],$param['is_terminal'],$param['merchant_id'],$param['member_id']);

        $param['update_uid']  = user_id();
        $param['update_time'] = datetime();

        $res = $model->where($pk, 'in', $ids)->update($param);
        if (empty($res)) {
            exception();
        }

        $param['ids'] = $ids;

        NoticeCache::del($ids);

        return $param;
    }

    /**
     * 公告删除
     *
     * @param array $ids  公告id
     * @param bool  $real 是否真实删除
     * 
     * @return array|Exception
     */
    public static function dele($ids, $real = false)
    {
        $model = new NoticeModel();
        $pk = $model->getPk();

        if ($real) {
            $res = $model->where($pk, 'in', $ids)->delete();
        } else {
            $update = delete_update();
            $res = $model->where($pk, 'in', $ids)->update($update);
        }
        if (empty($res)) {
            exception();
        }

        $update['ids'] = $ids;

        NoticeCache::del($ids);

        return $update;
    }
}
